import os
import logging

from google.appengine.dist import use_library
use_library('django', '1.2')

from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

class Student(db.Model):
  name = db.StringProperty(required=True)
  location = db.StringProperty(required=True)

  def GetNameAndLocation(self):
    return '%s is from %s' %(self.name, self.location)


class MapHandler(webapp.RequestHandler):
  def get(self):

    students = Student.all()
    locations = [student.location for student in students]
    names = [student.name for student in students]
    
    labels = []
    i = 0

    for name in names:
      label = 'f%s,000000,0,%d,10' % (name, i)
      labels.append(label)
      i += 1

    template_values = {'locations': '|'.join(locations), 'labels': '|'.join(labels), 'students': students}

    path = os.path.join(os.path.dirname(__file__), 'map.html')
    self.response.out.write(template.render(path, template_values))

  def post(self):

    name = self.request.get('name')
    location = self.request.get('location')
    student_to_delete = self.request.get('student')

    if name and location:
      student = Student(name=name, location=location)
      student.put()

    if students_to_delete:
      student = Student.get(student_to_delete)
      student.delete()

    self.get()

def main():
  application = webapp.WSGIApplication([('/', MapHandler)],
                                       debug=True)
  run_wsgi_app(application)

if __name__ == '__main__':
  main()
